package com.hdy.framework.common.service.impl;

import com.hdy.framework.common.dao.CommonDao;
import com.hdy.framework.common.dao.impl.CommonDaoImpl;
import com.hdy.framework.common.dto.Dto;
import com.hdy.framework.common.entity.Entity;
import com.hdy.framework.common.service.CommonService;
import com.hdy.framework.spring.entity.SpringContainer;
import com.hdy.utils.copy.Copyer;

public class CommonServiceImpl implements CommonService{
	
	private CommonDao commonDao;
	
	public <T> T getObjEntityById(Long id, Class<T> clazz){
		this.commonDao=SpringContainer.getBean("commonDao", CommonDaoImpl.class);
		return   (T)this.commonDao.findById(id, clazz);
	}
	public <T> Object getObjDtoById(Class<? extends T> dtoClazz,Class<T> entityClazz,Long id){
		this.commonDao=SpringContainer.getBean("commonDao", CommonDaoImpl.class);
		T entity =  (T)this.commonDao.findById(id, entityClazz);
		return   Copyer.copy(entity, dtoClazz);
	}
	public <T,D> Object getObjDtoById(Long id, Class<D> dtoClazz,Class<T> entityClazz){
		this.commonDao=SpringContainer.getBean("commonDao", CommonDaoImpl.class);
		Object entity =  this.commonDao.findById(id, entityClazz);
		Object d = null;
		try {
			d = dtoClazz.newInstance();
			Copyer.copy(entity, d);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return  d;
	}
	public Long saveEntity(Entity entity){
		this.commonDao=SpringContainer.getBean("commonDao", CommonDaoImpl.class);
		return this.commonDao.saveEntity(entity);
	}
	public <T> T saveDto(Long id,Dto dto,Class<T> entityClass ){
		this.commonDao=SpringContainer.getBean("commonDao", CommonDaoImpl.class);
		Entity  entity=null;
		if(id!=null){
			entity = (Entity) this.commonDao.findById(id, entityClass);
		}
		if(entity==null){
			try {
				entity= (Entity) entityClass.newInstance();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		Copyer.copy(dto, entity);
		this.commonDao.saveEntity(entity);
		return (T) entity;
	}
	public void setCommonDao(CommonDao commonDao) {
		this.commonDao = commonDao;
	}
	
}
